<template>
    <div class="public-account-management clearfix">
      <el-row>
        <el-col :lg="6">
        <div class="left">
          <div class="menu clearfix">
            <div  class="menu_bottom" v-for="(item, i) of menu.buttons" :key="i" >
              <!-- 一级菜单 -->
              <div   @click="menuFun(i,item)" class="menu_item" :class="{'active': isActive == i}"  draggable="true" @dragover.prevent="e=>e.preventDefault()" @dragstart="onDragStart(i,null,1)" @drop="onDragDrop(i,null,1)">
                {{item.name}}
                <el-button v-if="isActive === i" type="danger" icon="el-icon-delete" size="small" plain circle @click="deleteMenu(1,i)"></el-button>
              </div>
              <!--以下为二级菜单-->
              <div class="submenu" v-if="isSubMenuFlag == i">
                  <div class="subtitle" v-for="(subItem, k) in item.subButtons" :key="k">
                    <div draggable="true" @dragover.prevent="e=>e.preventDefault()" @dragstart="onDragStart(i,k,2)" @drop="onDragDrop(i,k,2)"  class="menu_subItem" :class="{'active': isSubMenuActive == i + '' +k}" @click="subMenuFun(item, subItem, i, k)">
                      {{subItem.name}}
                      <el-button v-if="isSubMenuActive === i + '' +k" type="danger" icon="el-icon-delete" size="small" plain circle @click="deleteMenu(2,i,k)"></el-button>
                    </div>
                  </div>
                  <!--  二级菜单加号， 当长度 小于  5 才显示二级菜单的加号  -->
                  <div class="menu_bottom menu_addicon" v-if="item.subButtons.length < 5" @click="addSubMenu(item)"><i ><el-icon><el-icon-plus/></el-icon></i></div>
              </div>
            </div>
            <!-- 一级菜单加号 -->
            <div class="menu_bottom menu_addicon" v-if="menuKeyLength < 3" @click="addMenu"><i><el-icon><el-icon-plus/></el-icon></i></div>
          </div>
        <el-button class="save_btn" type="success" @click="saveFun">保存并发布</el-button>
      </div>
      </el-col>
      <el-col :lg="10">
         <!--右边配置-->
         <div v-if="!showRightFlag" class="right">
				  <h2>编辑菜单</h2>
          <el-form :model="tempObj" :rules="rules" ref="menuForm" label-width="110px" label-position="left">
            <el-form-item label="菜单名称:" prop="name">
              <el-input v-model="tempObj.name" clearable placeholder="请输入菜单名称"></el-input>
            </el-form-item> 
            <el-form-item label="菜单类型：" prop="type">
						<el-radio-group v-model="tempObj.type">
              <el-radio :label="'view'">跳转链接</el-radio>
              <el-radio :label="'media_id'">发送素材</el-radio>
              <el-radio :label="'click'">发送关键词</el-radio>
              <el-radio :label="'miniprogram'">小程序</el-radio>
						</el-radio-group>
					</el-form-item>
          <el-form-item v-if="tempObj.type == 'media_id'" label="素材" prop="media_id">
              <el-input v-model="tempObj.media_id" readonly placeholder="请选择素材">
                <template #append>
                  <el-popover
                  placement="left"
                  width="700"
                  v-model="visible2">
                  <el-table
                    :data="tableData"
                    style="width: 100%">
                    <el-table-column
                      label="文件名"
                      width="600">
                      <template #default="scope">
                        <el-popover trigger="hover" placement="top">
                          <p>文件名: {{ scope.row.name }}</p>
                          <template #reference>
                            <div class="name-wrapper">
                                <el-tag size="medium">{{ scope.row.name }}</el-tag>
                            </div>
                          </template>
                        </el-popover>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作">
                      <template #default="scope">
                        <el-button
                          size="mini"
                          @click="handleEdit(scope.$index, scope.row)">选择</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <template #reference>
                    <el-button  type="success">选择素材(未完成)</el-button>
                  </template>
                </el-popover>
                </template>
              </el-input>
          </el-form-item> 
            <el-form-item v-if="tempObj.type == 'view'" label="跳转链接:" prop="url">
              <el-input v-model="tempObj.url" clearable placeholder="请输入链接"></el-input>
            </el-form-item> 
            <el-form-item v-if="tempObj.type == 'click'" label="关键词:" prop="key">
              <el-input v-model="tempObj.key" clearable placeholder="请输入关键词"></el-input>
            </el-form-item> 
            <el-form-item v-if="tempObj.type == 'miniprogram'" label="小程序的appid:" prop="appid">
              <el-input v-model="tempObj.appid" clearable placeholder="请输入小程序的appid"></el-input>
            </el-form-item> 
            <el-form-item v-if="tempObj.type == 'miniprogram'" label="小程序的appid:" prop="pagepath">
              <el-input v-model="tempObj.pagepath" clearable placeholder="请输入小程序的页面路径，如：pages/index"></el-input>
            </el-form-item>
          </el-form>
      </div>
      <div v-if="showRightFlag" class="right">
        <h2>编辑菜单</h2>
        <el-empty description="请点选菜单进行编辑" />
      </div>
    </el-col>
      <el-col :lg="8">
        <h2>menu对象值</h2>
        <pre class="menuJson" >{{menu}}</pre>
      </el-col>
      </el-row>
    </div>
  </template>
  <script>
    export default {
      name: 'officialAccountMenu',
      props: {},
      data(){
        return{
          appId:"",
          showRightFlag:true,//是否显示
          menu:{buttons:[]},
          tempObj:{},//当前选中菜单
          isActive: -1,// 选中index
          isSubMenuActive: -1,// 二级选中index
          isSubMenuFlag: -1,// 显示二级列表的index
          visible2: false,//素材内容  "选择素材"按钮弹框显示隐藏
          tableData:[], //素材内容弹框数据,
          dragTemp:{
              index:-1,
              subIndex:-1,
              grand:-1
          }
        }
      },
      created() {
        this.loadMpMenu();
      },
      mounted() {
        // this.httpGetData();
      },
      filters:{
      },
      methods:{
        async loadMpMenu(){
            if(!this.appId)return;
            const loading = this.$loading();
            let res = await this.$API.wechat.woaMenu.getMenu.get(this.appId);
            if(res.success){
              let menu = res.data.menu;
              this.menu = menu || {buttons:[]};
              console.log(this.menu)
            }
            loading.close();
        }, 
        // 素材内容弹框的选择按钮函数
        handleEdit(index, row) {
          this.visible2 = false;
          this.tempObj.media_id = row.name;
        },
        async saveFun(){
          console.log(this.menu);
          if(!this.appId){
            this.$message.warning("您还未选择需要发布菜单的公众号.");
            return;
          }
          let res = await this.$API.wechat.woaMenu.saveAndDeploy.post(this.appId,this.menu);
          if(res.success){
            this.$message.success("保存并发布成功!");
          }
        },
        // 一级菜单点击事件
        menuFun(i, item){
          this.showRightFlag = false;//右边菜单隐藏
          this.tempObj = item;//这个如果放在顶部，flag会没有。因为重新赋值了。
          this.isActive = i; //一级菜单选中样式
          this.isSubMenuFlag = i; //二级菜单显示标志
          this.isSubMenuActive = -1; //二级菜单去除选中样式
        },
        // 二级菜单点击事件
        subMenuFun(item, subItem, index, subIndex){
          this.showRightFlag = false;//右边菜单隐藏
          this.tempObj = subItem;//将点击的数据放到临时变量，对象有引用作用
          this.isSubMenuActive = index + "" + subIndex; //二级菜单选中样式
          this.isActive = -1;//一级菜单去除样式
        },
        // 添加横向一级菜单
        addMenu(){
          // 先判断1，再判断2,对象增加，会进行往下计算，所以必须先判断2，再判断1
          let menuName = "菜单"+(this.menuKeyLength + 1);
          this.menu.buttons.push(
            {
              type: "view",
              name: menuName,
              // url: "",//跳转链接
              // media_id:"",//素材名称--图文消息
              subButtons: []
            }
          );
        },
        // 添加横向二级菜单
        addSubMenu(item){
          let menuName = "子菜单"+(item.subButtons.length + 1);
          item.subButtons.push({
            type: "view",
            name: menuName,
            // url: "",//跳转链接
            // media_id:"",//素材名称--图文消息
          })
        },
        //删除当前菜单
        deleteMenu(grand,index,subIndex){
          this.$confirm('确定删除这个菜单吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if(grand === 1){ // 一级菜单的删除方法
              this.menu.buttons.splice(index,1);
            }else if(grand === 2){// 二级菜单的删除方法
              this.menu.buttons[index].subButtons.splice(subIndex, 1);
            }
            this.showRightFlag = true;
            this.$message.success("删除成功!");
          }).catch(() => {
  
          });
        },
        onDragStart(i,k,grand){
          this.dragTemp.index = i;
          this.dragTemp.subIndex = k;
          this.dragTemp.grand = grand;
        },
        onDragDrop(i,k,grand){
          console.log("从: "+this.dragTemp.index+" "+this.dragTemp.subIndex+" "+this.dragTemp.grand)
          console.log("到: "+i+" "+k+" "+grand)
          if(this.dragTemp.index < 0) return;
          if(grand === this.dragTemp.grand && this.dragTemp.index === i && this.dragTemp.subIndex === k){ 
            console.log("放回原位...")
            return;//放回原位
          }
          if(this.dragTemp.grand < grand){//菜单 到 子菜单(不允许)
            this.$message.warning("父菜单无法拖拽到子菜单");
            return;
          }
          if(this.dragTemp.grand === 1 && grand === 1){ //菜单 到 菜单
            let from = this.dragTemp.index;
            let to = i;
            if(this.dragTemp.index > i){
              from = i;
              to = this.dragTemp.index;
            }//确认调换顺序
            let list = this.menu.buttons;//确认调换顺序的元素
            let spliceObj = list.splice(to,1,list[from])[0]
            list.splice(from,1,spliceObj)
          }else if(this.dragTemp.grand === 2 && grand === 2){ //子菜单 到 子菜单
            let from = this.dragTemp.subIndex;
            let to = k;
            if(this.dragTemp.subIndex > k){
              from = k;
              to = this.dragTemp.subIndex;
            }//确认调换顺序
            let list = this.menu.buttons[i].subButtons;//确认调换顺序的元素
            let spliceObj = list.splice(to,1,list[from])[0]
            list.splice(from,1,spliceObj)
          }else if(this.dragTemp.grand === 2 && grand === 1){//子菜单 到 另一个菜单
            let aimButton = this.menu.buttons[i];//目标button
            if(aimButton.subButtons?.length >= 5){
                this.$message.error('目标组已满');
                return;
            }
            let list = this.menu.buttons[this.dragTemp.index].subButtons;
            let spliceObj = list.splice(this.dragTemp.subIndex,1)[0];
            
            if(!aimButton.subButtons)aimButton.subButtons = [];
            aimButton.subButtons.push(spliceObj);
          }
          
        }
      },
      computed:{
        // menuObj的长度，当长度 小于  3 才显示一级菜单的加号
        menuKeyLength:function(){
          return this.menu.buttons.length;
        }
      },
      components: {
      }
    }
  </script>
  <!--本组件样式-->
  <style lang="scss" scoped="scoped">
    h2 {font-size: 17px;color: #3c4a54;padding:0 0 30px 0;}
    [data-theme="dark"] h2 {color: #fff;}
    /* 公共颜色变量 */
    .clearfix{*zoom:1;}
    .clearfix::after{content: "";display: table; clear: both;}
    div{
      text-align: left;
    }
    .public-account-management{
      background-color: #fff;
      min-width: 1200px;
      padding:30px 30px 150px 30px;
      .left{
        display: inline-block;
        width: 305px;
        height: 630px;
        background-image:url('../../../../assets/img/iphone_backImg.png');
        background-repeat: no-repeat;
        background-size: 100% auto;
        padding: 501px 22px 88px;
        position: relative;
        box-sizing: border-box;
        /*第一级菜单*/
        .menu{
          .menu_bottom{
            position: relative;
            float: left;
            display: inline-block;
            box-sizing: border-box;
            width: 87px;
            /*height: 44px;*/
            /*line-height: 44px;*/
            text-align: center;
            background-color: #e2e2e2;
            border: 1px solid #ebedee;
            cursor: pointer;
            &.menu_addicon{
              height: 46px;
              line-height: 46px;
            }
            .menu_item{
              height: 44px;
              line-height: 44px;
              /*padding: 14px 0;*/
              text-align: center;
              box-sizing: border-box;
              &.active{
                border: 1px solid #2bb673;
              }
            }
            .menu_subItem{
              height: 44px;
              line-height: 44px;
              text-align: center;
              box-sizing: border-box;
              /*padding: 14px 0;*/
              &.active{
                border: 1px solid #2bb673;
              }
            }
          }
            i{
              color:#2bb673;
            }
          /*第二级菜单*/
          .submenu{
            position: absolute;
            width: 87px;
            bottom: 45px;
            .subtitle{
              background-color: #e8e7e7;
              box-sizing: border-box;
              margin-bottom: 2px;
            }
          }
        }
        .save_btn{
          position: absolute;
          bottom: -50px;
          left: 100px;
        }
      }
      /*右边菜单内容*/
      .right{
        height: 710px;
        margin-right: 20px;
      }

      .menuJson{
        width:100%;
        height:710px; 
        font-size: 15px;
        color: #333;
        border: 1px #3333332f solid;
        border-radius: 5px;
        padding:20px;
        background: #fff;
        font-family: consolas;
        line-height: 1.5;
        overflow: auto;
      }
    }
  </style>